package cn.mhome.merchant.dao.spring.data.repository;
import java.io.Serializable;

import javax.persistence.EntityManager;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

public class CriteriaRepositoryFactoryBean<R extends JpaRepository<T, ID>, T, ID extends Serializable>
		extends JpaRepositoryFactoryBean<R, T, ID> {

	protected RepositoryFactorySupport  createRepositoryFactory(EntityManager entityManager) {
		return new CriteriaRepositoryFactory<T, ID>(entityManager);
	}

	private static class CriteriaRepositoryFactory<T, ID extends Serializable> extends
			JpaRepositoryFactory {
		private EntityManager entityManager;

		public CriteriaRepositoryFactory(EntityManager entityManager) {
			super(entityManager);
			this.entityManager = entityManager;
		}

		@SuppressWarnings("unchecked")
		protected Object getTargetRepository(RepositoryMetadata metadata) {
			return new CriteriaRepositoryImpl<T, ID>((Class<T>) metadata.getDomainType(), entityManager);
		}

		protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
			return CriteriaRepository.class;
		}
	}
}
